package com.pubg.dao;


import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 数据库连接帮助类
 * @author ZhangYuBiao
 */
public class BaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String pwd;

    static {
        String fileName = "database.properties";
        Properties prsMap = new Properties();
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(fileName);
        try {
            //解析配置对象
            prsMap.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver = prsMap.getProperty("mysql.driver");
        url = prsMap.getProperty("mysql.url");
        username = prsMap.getProperty("mysql.username");
        pwd = prsMap.getProperty("mysql.password");
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开数据连接
     *
     * @return
     */
    public Connection openConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, pwd);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭对象 释放资源
     *
     * @param resultSet
     * @param preparedStatement
     * @param connection
     */
    public void closeAll(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行增删改
     *
     * @param sql     需要执行的sql语句
     * @param objects 入参
     * @return 操作结果
     */
    public int executeUpdate(String sql, Object... objects) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = openConnection();
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < objects.length; i++) {
                preparedStatement.setObject((i + 1), objects[i]);
            }
            return preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            closeAll(null, preparedStatement, connection);
        }

    }
}
